package com.cst.intercepterdemo.intercepter;

import com.cst.intercepterdemo.context.IInterceptContext;
import com.cst.intercepterdemo.mapper.ApplicationMapper;
import com.cst.intercepterdemo.model.Application;
import com.cst.intercepterdemo.model.ApplicationExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <ul>
 * <li>文件名称 : com.cst.intercepterdemo.intercepter.ApplicationValidator
 * </li>
 * <li>版权所有 : 版权所有(C)2016-2020</li>
 * <li>公 司 : CST</li>
 * <li>创建时间 : 2016/12/9</li>
 * <li>修改记录 : </li>
 * </ul>
 * 类说明：
 *
 * @author Allen
 * @version 1.0
 */
public abstract class AbstractApplicationValidator implements IRequestIntercepter {

    private Logger logger = LoggerFactory.getLogger(AbstractApplicationValidator.class);

    private static final String APP_CACHE_KEY = "app";

    @Autowired
    private ApplicationMapper appDao;

    @Override
    public boolean doIntercept(IInterceptContext context) {
        String app = context.getRequest().getParameter("appId");
        if(StringUtils.isEmpty(app)){
            context.addErrorCode("param.app.not.exist");
            return false;
        }
        Application application = getApplication(context);
        if(application==null){
            context.addErrorCode("app.not.exist");
            logger.info("[app exist] valide:{}",false);
            return false;
        }
        return doAppIntercept(application,context);
    }

    protected abstract boolean doAppIntercept(Application application,IInterceptContext context);

    private Application getApplication(IInterceptContext context){

        Object cachedApplication = context.getCache(APP_CACHE_KEY);
        if(cachedApplication !=null){
            logger.info("get app from cache.");
            return (Application)cachedApplication;
        }

        String app = context.getRequest().getParameter("appId");
        ApplicationExample example = new ApplicationExample();
        example.createCriteria().andIdEqualTo(Integer.parseInt(app));
        List<Application> applications = appDao.selectByExample(example);
        if(applications==null || applications.size()==0){
            return null;
        }
        context.cache(APP_CACHE_KEY,applications.get(0));
        return applications.get(0);
    }
}
